package com.ayou.healthmanagement.controller;



import cn.hutool.captcha.LineCaptcha;
import com.ayou.healthmanagement.utils.CaptchaUtils;
import com.ayou.healthmanagement.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CaptchaUtils captchaUtil;

    @GetMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        LineCaptcha code = captchaUtil.createCode();
        // 输出图片到页面
        code.write(response.getOutputStream());
        // 保存code到缓存
        System.out.println("存入的验证码"+code.getCode());
        //60秒后失效
        redisUtil.set("code",code.getCode(),60);
        //响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将生成的图片通过流的形式返回给前端
        ImageIO.write(code.getImage(),"JPEG",outputStream);
//        return Result.success(captcha);

    }

    public boolean validateCaptcha(HttpServletRequest request, String code) {
        String sessionCaptcha = (String) request.getSession().getAttribute("code");
        if (sessionCaptcha != null && sessionCaptcha.equalsIgnoreCase(code)) {
            request.getSession().removeAttribute("code");
            return true;
        }
        return false;
    }

}
